/*
 * Copyright (c) 2016 YCY Group Holding Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 *
 * $Id: TopicReceiver.java  2016-7-7 下午3:17:14 jackLiang $
 */
package com.jack.mq.topic;

import javax.jms.Connection;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageListener;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.jms.Topic;

import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;

/**
 * @author JackLiang
 * @date 2016-7-7
 * @version 1.0.0
 */
public class TopicReceiver {

    // tcp 地址

    public static final String BROKER_URL = "tcp://localhost:61616";

    // 目标，在ActiveMQ管理员控制台创建 http://localhost:8161/admin/queues.jsp
    public static final String TARGET     = "jack.mq.topic";

    public static void run() throws Exception {

        Connection connection = null;

        Session session = null;

        Topic topic = null;

        // 消费者，消息接收者
        MessageConsumer consumer;

        ActiveMQConnectionFactory factory = null;
        try {

            // 创建链接工厂
            factory = new ActiveMQConnectionFactory(ActiveMQConnection.DEFAULT_USER,
                                                    ActiveMQConnection.DEFAULT_PASSWORD, BROKER_URL);

            // 通过工厂创建一个连接
            connection = factory.createTopicConnection();

            // 启动连接
            connection.start();

            // 创建一个session会话
            session = connection.createSession(Boolean.TRUE, Session.AUTO_ACKNOWLEDGE);

            // 创建一个消息队列
            topic = session.createTopic(TARGET);

            // 创建消息制作者
            consumer = session.createConsumer(topic);

            consumer.setMessageListener(new MessageListener() {

                public void onMessage(Message msg) {
                    System.out.println("开始接收消息");
                    if (msg != null) {
                        if (msg instanceof TextMessage) {
                            TextMessage textMessage = (TextMessage) msg;
                            try {
                                System.out.println("-接收到消息---" + textMessage.getText());
                            } catch (JMSException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }

            });

            session.commit();
        } catch (Exception e) {
            throw e;
        } finally {

            // 关闭释放资源
            if (session != null) {
                session.close();
            }

            if (connection != null) {
                connection.close();
            }
        }

    }

    public static void main(String[] args) throws Exception {

        TopicReceiver.run();

    }
}
